package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

public class TagListAdapter extends CursorAdapter implements Filterable {
	private BuxoidDb mDb;
	private boolean mRootTagsOnly;
	private String mText;
	
	public TagListAdapter(Context context, Cursor c, BuxoidDb db, boolean rootTagsOnly) {
	    super(context, c);
	    mDb = db;
	    mRootTagsOnly = rootTagsOnly;
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final LayoutInflater inflater = LayoutInflater.from(context);
		final TextView view = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
		view.setText(cursor.getString(cursor.getColumnIndex(BuxoidDb.TAG_NAME)));
		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		TextView tv = (TextView) view;
		tv.setText(cursor.getString(cursor.getColumnIndex(BuxoidDb.TAG_NAME)));
	}

	@Override
	public String convertToString(Cursor cursor) {
		return (mText != null ? mText: "") + cursor.getString(cursor.getColumnIndex(BuxoidDb.TAG_NAME));
	}

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		if (getFilterQueryProvider() != null) {
            return getFilterQueryProvider().runQuery(constraint);
        }
   
        String where = "";
        if (constraint != null) {
        	where = constraint.toString();
        	// if the user enters a comma, then just take the last bit
        	int i = where.lastIndexOf(",");
        	if (i > -1) {
        		mText = where.substring(0, i+1) + " ";
        		where = where.substring(i+1).trim();
//        		Log.d("Buxfer", where);
        	}
        }
        
        Cursor cur = null;
        if (where.length() > 1) {
        	cur = mDb.fetchTags(BuxoidDb.TAG_NAME + " like '" + where + "%'" + (mRootTagsOnly ? " AND " + BuxoidDb.TAG_PARENT + " = -1": ""));
        }
        
        return cur;
	}
}